import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react'
import { Map, View, proj } from 'ol'
import { get } from 'ol/proj'
import { Point } from 'ol/geom'
import { getWidth, getTopLeft } from 'ol/extent'
import { Tile } from 'ol/layer'
import { XYZ, WMTS as WMTSSource } from 'ol/source'
import WMTS from 'ol/tilegrid/WMTS'
import ZoneApi from '../../../utils/apis/ZoneApi'
import { GeoJSON } from 'ol/format'
import { createLayer, geomToWkt } from '../../../utils/helper/mapHelper'
import { Button, Input, Modal } from 'antd'
import Draw from 'ol/interaction/Draw';
import TileLayer from 'ol/layer/Tile';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';
import { Circle, Text as TextStyle } from 'ol/style';
import './index.less'

const token = 'e54ba40524CFGW353983955577c7a0a2'

// const labelUrl = 'https://t{0-6}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=ca5065da88c3e8841d2a9f34035d5270'
// const imageUrl = 'https://t{0-6}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=ca5065da88c3e8841d2a9f34035d5270'
const labelUrl = `http://218.200.175.176:20202/services/ybgis_domdlg/wmts?ak=${token}`
const imageUrl = `http://218.200.175.176:20202/services/ybgis_dom/wmts?ak=${token}`

let draw;
const drawLayer = createLayer();

const createTileLayer = (url) => {
    let projection = get('EPSG:4326');
    //web墨卡托坐标系地图服务使用EPSG:3857
    // let projection = ol.proj.get('EPSG:3857');
    let projectionExtent = projection.getExtent();
    let size = getWidth(projectionExtent) / 256;
    let resolutions = new Array(19);
    let matrixIds = new Array(19);
    for (let z = 0; z < 19; ++z) {
        //根据坐标系获取地图各个缩放级别比例尺
        resolutions[z] = size / Math.pow(2, z);
        matrixIds[z] = z;
    }
    return new Tile({
        // source: new XYZ({
        //     wrapX: false,
        //     // url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
        //     url: imageUrl

        // })
        source: new WMTSSource({
            //toomap发布的矢量瓦片地图服务+浏览器端测试令牌
            // url: `/map-services/newtianditudom/wmts?ak=${token}`,
            url: url,
            //wmts服务元数据中指定的layer值
            layer: 'defaultLayer',
            //wmts服务元数据中指定的style值
            style: 'default',
            //wmts服务元数据中指定的matrixSet值
            matrixSet: 'GetTileMatrix',
            //wmts服务元数据中指定的format值
            format: 'image/png',
            //定义的投影对象
            projection: projection,
            crossOrigin: "anonymous",
            // tileLoadFunction: (imageTile, src) => {
            //     debugger
            //     imageTile.getImage().src = src;
            // },
            tileGrid: new WMTS({
                //定义瓦片服务的原点
                origin: getTopLeft(projectionExtent),
                //定义瓦片服务的各级比例尺
                resolutions: resolutions,
                //定义瓦片服务的级别
                matrixIds: matrixIds,
            }),
        })
    })
}

const BusinessMap = forwardRef((props, ref) => {
    const mapRef = useRef();
    const [map, setMap] = useState();
    const [panelKey, setPanelKey] = useState();
    const [mapGlobal, setMapGlobal] = useState({});
    const { autoFit = false } = props;

    useImperativeHandle(ref, () => {
        return {
            map: map
        }
    })

    useEffect(() => {
        const baseImageLayer = createTileLayer(imageUrl)

        const labelLayer = createTileLayer(labelUrl)

        const m = window.mmm = new Map({
            view: new View({
                center: [104.63409743302516, 28.390470472124225],
                zoom: 9,
                projection: 'EPSG:4326',
                minZoom: 5
            }),
            layers: [baseImageLayer, labelLayer],
            target: mapRef.current,
            controls: [],

        });

        const view = new View({
            center: [104.7608, 28.5586], // 地图中心点经纬度
            zoom: 8, // 初始缩放级别
            projection: 'EPSG:4326',
            minZoom: 5
        });
        const globalLayer = new TileLayer({
            source: new XYZ({
                crossOrigin: 'anonymous',
                url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
            }),
        });

        m.addLayer(drawLayer)
        setMap(m);
        // m.getLayers().insertAt(0, globalLayer);
    }, [])

    useEffect(() => {

        if (map) {
            const zoneLayer = createLayer((feature) => {
                feature.set('yqColors', 'yqColor')
                //console.log('feature地图函数内部', feature)
                //监测预警_降雨量设置区域颜色
                //3.28 注：这个地方可以设置部分颜色值，然后传入相应值绝地区块地图颜色，不在此进行具体临界值判断逻辑，
                const jyl = props.jyl?.filter(e => e.name === feature.get('name'))?.[0]?.value
                let colors = 'rgba(0,0, 0, 0)';
                if (feature.get('name')) {
                    if (jyl < 25) {
                        colors = 'rgba(56,101,240,0.5)'
                    } else if (jyl >= 25 && jyl < 50) {
                        colors = 'rgba(247,245,0,0.5)'
                    }else if(jyl>=50 && jyl<100){
                        colors='rgba(235,142,0,0.5)'
                    }else if(jyl>=100){
                        colors = 'rgba(197,34,36,0.5)'
                    }
                    // if (jyl >= 0.1 && jyl < 10) {
                    //     colors = 'rgba(219,247, 211, 0.5)';
                    // } else if (jyl >= 10 && jyl < 25) {
                    //     colors = 'rgba(62,186, 57, 0.5)';
                    // } else if (jyl >= 25 && jyl < 50) {
                    //     colors = 'rgba(96,184, 249, 0.5)';
                    // } else if (jyl > 50 && jyl < 100) {
                    //     colors = 'rgba(0,0, 255, 0.5)';
                    // } else if (jyl >= 100 && jyl < 250) {
                    //     colors = 'rgba(255,0, 255, 0.5)';
                    // } else if (jyl >= 250 && jyl <= 999) {
                    //     colors = 'rgba(255,0, 0, 0.5)';
                    // } else 
                    if (jyl === '1000') {//橙色
                         colors='rgba(235,142,0,0.5)'
                    } else if (jyl === '1001') {//黄色
                        colors = 'rgba(247,245,0,0.5)'
                    } else if (jyl === '1002') {//蓝色
                         colors = 'rgba(56,101,240,0.5)'
                    }else if (jyl === '1003') {//红色
                        colors = 'rgba(255,255, 0, 0.5)';
                    }

                }
                return [new Style({
                    fill: new Fill({
                        color: colors
                    }),
                    stroke: new Stroke({
                        color: 'rgb(255,255,0)',
                        width: 3,
                    }),
                }), new Style({
                    geometry: new Point(feature.get('centroid') || feature.get('center')),
                    text: new TextStyle({
                        font: 'bold 16px sans-serif',
                        text: feature.get('name'),
                        fill: new Fill({
                            color: 'rgba(255,255,255)'
                        }),
                        // stroke: new Stroke({
                        //     color: 'rgb(0,0,0)',
                        //     width: 3,
                        // }),
                        backgroundFill: new Fill({
                            color: '#7EBDE0'
                        }),
                        backgroundStroke: new Stroke({
                            color: '#7EBDE0',
                            width: 2,
                            lineCap: 'round'
                        }),
                        padding: [3, 6, 2, 6]
                    })
                })]
            }, [])
            zoneLayer.set('layerName', '区县图层颜色')

            map.addLayer(zoneLayer);

            ZoneApi.root().then(resp => {
                const geojsonFormat = new GeoJSON();
                const feature = geojsonFormat.readFeature(resp);

                ZoneApi.children().then(resp => {
                    const geojsonFormat = new GeoJSON();
                    const features = geojsonFormat.readFeatures(resp);

                    //zoneLayer.getSource().clear();


                    zoneLayer.getSource().addFeatures(features);
                    //console.log('feature11111', zoneLayer)
                    let hasFit = false;
                    if (window.userAreaCode) {
                        const targetFeature = features.find(f => {
                            return f.get('adcode')?.toString() === window.userAreaCode
                        });
                        if (targetFeature) {
                            const geom = targetFeature.getGeometry().clone();
                            geom.scale(2);
                            map.getView().fit(geom);
                            hasFit = true;
                        }
                    }
                    if (!hasFit) {
                        const geom = feature.getGeometry().clone();
                        geom.scale(1.5);
                        autoFit && map.getView().fit(geom);
                    }

                })
            })
        }
    }, [map, autoFit, props.jyl])
    function addInteraction(type) {

        draw = new Draw({
            source: drawLayer.getSource(),
            type: type,
        });
        draw.on('drawend', (evt) => {
            // console.log(evt)
            const geom = evt.feature.getGeometry();
            const wkt = geomToWkt(geom);
            Modal.info({
                title: "wkt字符串",
                content: <Input.TextArea rows={10} value={wkt} />
            })
        })
        map.addInteraction(draw);
    }

    return <BusinessMap.Context.Provider value={{
        map: map,
        setPanelKey,
        panelKey,
        mapGlobal,
        setMapGlobal
    }}>
        <div ref={mapRef} style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0
        }}>

        </div>
        {props.children}
        <div style={{
            pointerEvents: 'none'
        }}>
            <div className='custom-circle'>
                <div className='animation'>
                    <div className='circle wh100' style={{
                        backgroundImage: `url(${process.env.PUBLIC_URL}/images/光圈3.png)`,
                        backgroundSize: '100% 100%',
                    }}></div>
                    <div className='circle wh100' style={{
                        backgroundImage: `url(${process.env.PUBLIC_URL}/images/光圈1.png)`,
                        backgroundSize: '100% 100%',
                    }}></div>
                    <div className='circle wh100' style={{
                        backgroundImage: `url(${process.env.PUBLIC_URL}/images/光圈2.png)`,
                        backgroundSize: '100% 100%',
                    }}></div>
                    <div className='circle wh100' style={{
                        backgroundImage: `url(${process.env.PUBLIC_URL}/images/光圈4.png)`,
                        backgroundSize: '100% 100%',
                    }}></div>
                </div>
                {/* <div>
                <div className='circle wh100' style={{
                    backgroundImage: `url(${process.env.PUBLIC_URL}/images/光圈5.png)`,
                    backgroundSize: '100% 100%',
                }}></div>
            </div> */}
            </div>

            {/* <div className='little-circle' style={{
            backgroundImage: `url(${process.env.PUBLIC_URL}/images/光圈5.png)`
        }}></div> */}
            <div className='shot' style={{
                backgroundImage: `url(${process.env.PUBLIC_URL}/images/射光.png)`,
                backgroundSize: '100% 100%',
            }}></div>
            <div className='circle-static' style={{
                backgroundImage: `url(${process.env.PUBLIC_URL}/images/光圈不动.png)`,
                backgroundSize: '100% 100%',
            }}></div>
        </div>
        {/* <div style={{
            position: "absolute",
            right: 20,
            bottom: 20
        }}>
            <Button.Group>
                <Button onClick={e => {
                    map.removeInteraction(draw);
                    addInteraction('Point');
                }}>点</Button>
                <Button onClick={e => {
                    map.removeInteraction(draw);
                    addInteraction('LineString');
                }}>线</Button>
                <Button onClick={e => {
                    map.removeInteraction(draw);
                    addInteraction('Polygon');
                }}>面</Button>
            </Button.Group>
        </div> */}
    </BusinessMap.Context.Provider>;
})
BusinessMap.Context = React.createContext();

export default BusinessMap;